/* eslint-disable eqeqeq */
/**
 * request 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import { history } from "umi";
import { message } from "antd";
import { extend } from "umi-request";

const errorHandler = (error) => {
  const { response } = error;
  // if (response && response.status) {
  //   const errorText = codeMessage[response.status] || response.statusText;
  //   const { status, url } = response;
  //   if (response?.url.indexOf('api/user_token') == -1) {
  //     notification.error({
  //       message: `请求错误 ${status}: ${url}`,
  //       description: errorText,
  //     });
  //   }
  // } else if (!response) {
  //   if (response?.url.indexOf('api/user_token') == -1) {
  //     notification.error({
  //       description: '您的网络发生异常，无法连接服务器',
  //       message: '网络异常',
  //     });
  //   }
  // }

  return response ? response : {};
};
/**
 * 配置request请求时的默认参数
 */

const request = extend({
  prefix: REACT_APP_URL, //前缀代理  tasks.nangaoyun.com
  errorHandler,
  // 默认错误处理
  credentials: "include", // 默认请求是否带上cookie
});

// request拦截器, 改变url 或 options.
request.interceptors.request.use(async (url, options) => {
  let token = localStorage.getItem("TOKENSTRING");
  if (token) {
    const headers =
      options.type == "form"
        ? {
            Authorization: token,
          }
        : {
            "Content-Type": "application/json",
            Authorization: token,
          };
    return {
      url: url,
      options: { ...options, headers: headers },
    };
  }
});

// response拦截器, 处理response
request.interceptors.response.use(async (response, options) => {
  if (options.url === "/webtool/v1/storeexport"|| options.url === "/webtool/v1/purchaseexport") {
    const data = await response.clone().blob();
    let blobUrl = window.URL.createObjectURL(data);
    const a = document.createElement("a");
    a.style.display = "none";
    let pathname = options.params.filename;
    a.download = pathname + ".xls";
    a.href = blobUrl;
    a.click();
    a.remove();
    return;
  }
  const data = await response.clone().json();

  // 详情返回的response处理
  if (data?.code !== 0) {
    if (data?.error || data?.code === -1) {
      console.log(location.origin);
      localStorage.removeItem("TOKENSTRING");
      history.replace("/user/login");
    } else {
      message.error(data?.msg);
    }
  }

  return response;
});

export default request;
